package hk.edu.polyu.comp446.group5;

import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

public class GraphGenerator extends JFrame {
	public void GraphGenerator() {
	}

	public GraphGenerator(String s, String type) {
		super(s);
		JFreeChart jfreechart;

		if (type.equalsIgnoreCase("cc")) {
			jfreechart = createChart_ccReturn(s);
		} else {
			jfreechart = createChart(s);
		}
		ChartPanel chartpanel = new ChartPanel(jfreechart, true, true, true, false, true);
		chartpanel.setPreferredSize(new Dimension(800, 470));
		setContentPane(chartpanel);
	}

	public static JFreeChart createChart(String stockName) {

		// String stockName = "vbisx";
		XYDataset xydataset = createPriceDataset(stockName);
		//XYDataset xydataset = createCCreturnDataset(stockName);

		String s = "Stock Price for " + stockName;
		JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(s, "Date", "Price", xydataset, true, true, false);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis();
		numberaxis.setLowerMargin(0.40000000000000002D);
		DecimalFormat decimalformat = new DecimalFormat("00.00");
		numberaxis.setNumberFormatOverride(decimalformat);
		XYItemRenderer xyitemrenderer = xyplot.getRenderer();
		xyitemrenderer
				.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
		NumberAxis numberaxis1 = new NumberAxis("Volume");
		numberaxis1.setUpperMargin(1.0D);
		xyplot.setRangeAxis(1, numberaxis1);
		//xyplot.setDataset(1, createVolumeDataset());
		xyplot.setRangeAxis(1, numberaxis1);
		xyplot.mapDatasetToRangeAxis(1, 1);
		XYBarRenderer xybarrenderer = new XYBarRenderer(0.20000000000000001D);
		xybarrenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat(
				"0,000.00")));
		xyplot.setRenderer(1, xybarrenderer);
		ChartUtilities.applyCurrentTheme(jfreechart);
		xybarrenderer.setBarPainter(new StandardXYBarPainter());
		xybarrenderer.setShadowVisible(false);
		return jfreechart;
	}

	public static JFreeChart createChart_ccReturn(String stockName) {
		// String stockName = "vbisx";
		// XYDataset xydataset = createPriceDataset(stockName);

		XYDataset xydataset = createCCreturnDataset(stockName);

		String s = "Continuously Compounded Returns for " + stockName;
		JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(s, "Date", "Price", xydataset, true, true, false);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis();
		numberaxis.setLowerMargin(0.40000000000000002D);
		DecimalFormat decimalformat = new DecimalFormat("00.00");
		numberaxis.setNumberFormatOverride(decimalformat);
		XYItemRenderer xyitemrenderer = xyplot.getRenderer();
		xyitemrenderer
				.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
		NumberAxis numberaxis1 = new NumberAxis("Volume");
		numberaxis1.setUpperMargin(1.0D);
		xyplot.setRangeAxis(1, numberaxis1);
		// xyplot.setDataset(1, createVolumeDataset());
		xyplot.setRangeAxis(1, numberaxis1);
		xyplot.mapDatasetToRangeAxis(1, 1);
		XYBarRenderer xybarrenderer = new XYBarRenderer(0.20000000000000001D);
		xybarrenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})", new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat(
				"0,000.00")));
		xyplot.setRenderer(1, xybarrenderer);
		ChartUtilities.applyCurrentTheme(jfreechart);
		xybarrenderer.setBarPainter(new StandardXYBarPainter());
		xybarrenderer.setShadowVisible(false);
		return jfreechart;
	}

	private static XYDataset createPriceDataset(String stock) {
		TimeSeries timeseries = new TimeSeries("Price");

		try {
			// Open the file that is the first command line parameter
			stock = stock.toLowerCase();
			FileInputStream fstream = new FileInputStream(stock + ".txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				//System.out.println(strLine);  // Print text file content, for Debug use.

				String[] stockdataArry = strLine.split(",");

				String[] date = stockdataArry[1].split("-");
				int[] dateInt = convertStringArraytoIntArray(date);
				double stockPrice = Double.parseDouble(stockdataArry[2]);

				timeseries.add(new Day(dateInt[2], dateInt[1], dateInt[0]), stockPrice);
			}
			// Close the input stream
			in.close();
		} catch (Exception e) { // Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}

		return new TimeSeriesCollection(timeseries);
	}

	private static XYDataset createCCreturnDataset(String stock) {
		TimeSeries timeseries = new TimeSeries("Price");

		try {
			// Open the file that is the first command line parameter
			stock = stock.toLowerCase();
			FileInputStream fstream = new FileInputStream(stock + ".txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			// Read File Line By Line
			double[] allData = new double[61];
			String[] dateData = new String[61];
			int i = 0;
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				//System.out.println(strLine);
				String[] stockdataArry = strLine.split(",");
				dateData[i] = stockdataArry[1];
				allData[i] = Double.parseDouble(stockdataArry[2]);
				i++;
			}

			FinancialCore financialCore = new FinancialCore("CCReturn");
			double[] ccArry = financialCore.returnsType(allData);
			for (int k = 0; k < ccArry.length; k++) {
				System.out.println(ccArry[k]);

				String[] date = dateData[k].split("-");
				int[] dateInt = convertStringArraytoIntArray(date);
				timeseries.add(new Day(dateInt[2], dateInt[1], dateInt[0]), ccArry[k]);
			}

			/*
			 * int k=0; while ((strLine = br.readLine()) != null) { // Print the
			 * content on the console System.out.println(strLine);
			 * 
			 * String[] stockdataArry = strLine.split(",");
			 * 
			 * String[] date = stockdataArry[1].split("-");
			 * 
			 * int[] dateInt = convertStringArraytoIntArray(date); double
			 * stockPrice = ccArry[k];
			 * 
			 * System.out.println(stockPrice); k++; timeseries.add(new
			 * Day(dateInt[2], dateInt[1], dateInt[0]), stockPrice); }
			 */

			// Close the input stream
			in.close();
		} catch (Exception e) { // Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}

		return new TimeSeriesCollection(timeseries);
	}

	public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
		if (sarray != null) {
			int intarray[] = new int[sarray.length];
			for (int i = 0; i < sarray.length; i++) {
				intarray[i] = Integer.parseInt(sarray[i]);
			}
			return intarray;
		}
		return null;
	}
}